import React, { useCallback, useMemo } from 'react'
import { Image, Text, View } from '@tarojs/components'
import { convertPx, getNavBar, getPlatform } from '@UTILS/common'
import Taro from '@tarojs/taro'
import Images from '@ASSET/Images'
import Navigate from '@NAVIGATION/navigateManager'
import style from './NavBar.module.scss'

const { isWeb } = getPlatform()

interface Props {
  title: string
  backgroundColor?: string
  titleColor?: string
  barContent?: JSX.Element | (() => JSX.Element) | null
  containerClass?: string
  showIcon?: boolean
  hiddenBack?: boolean
  contentClickable?: boolean
  isWhiteIcon?: boolean
}

const NavBar: React.FC<Props> = ({
  title, backgroundColor, titleColor, barContent,
  containerClass, showIcon = true, contentClickable = false,
  isWhiteIcon, hiddenBack
}) => {
  const heightStyle = useMemo(() => getNavBar(), [])
  const goHome = useMemo(() => Taro.getCurrentPages().length === 1, [])
  const backIcon = isWhiteIcon ? Images.nav.back_white : Images.nav.normal_back
  const iconSrc = (goHome && !isWeb) ? Images.nav.go_home : backIcon
  const containerStyle = useMemo(() => {
    const cusStyle = {
      height: convertPx(heightStyle.navBarHeight),
      paddingTop: heightStyle.statusBarHeight,
    }
    if (backgroundColor) {
      backgroundColor && Object.assign(cusStyle, { backgroundColor })
    }
    return cusStyle
  }, [backgroundColor, heightStyle.navBarHeight, heightStyle.statusBarHeight])
  const titleStyle = useMemo(() => ({ color: titleColor }), [titleColor])
  const renderContent = useCallback(() => {
    if (barContent && typeof barContent === 'object') {
      return barContent
    }
    if (barContent) {
      return barContent()
    }
    return (
      <View className={style.titleContainer}>
        <Text className={`${style.titleText} ${showIcon ? style.showIcon : ''}`} style={titleStyle}>{title}</Text>
      </View>
    )
  }, [barContent, showIcon, title, titleStyle])
  const onClickBack = useCallback(e => {
    if (!goHome && hiddenBack) return
    e?.stopPropagation?.()
    if (goHome && !isWeb) {
      Navigate.switchTab('homePage')
    } else {
      Navigate.navigateBack(1)
    }
  }, [goHome, hiddenBack])

  const onClickContainer = useCallback(() => {
    if (!contentClickable) return
    onClickBack(null)
  }, [contentClickable, onClickBack])

  return (
    <View className={`${style.container} ${containerClass} ${style.nativeNav}`} style={containerStyle} onClick={onClickContainer}>
      {showIcon && (
        <View className={`${style.iconContainer} ${!goHome && hiddenBack ? style.hidden : ''}`} onClick={onClickBack}>
          <Image src={iconSrc} className={style.icon} />
        </View>
      )}
      {renderContent()}
    </View>
  )
}
export default NavBar
